package com.haven.webrobotserver.service.impl;

import com.haven.webrobotserver.dao.mybatis.mapper.*;
import com.haven.webrobotserver.domain.*;
import com.haven.webrobotserver.domain.vo.TestcaseVO;
import com.haven.webrobotserver.service.ExecuteService;
import com.haven.webrobotserver.task.Task;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@Service
public class ExecuteSeriveImpl implements ExecuteService {

    private final org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired(required = false)
    private TestcaseTestdataMapper testcaseTestdataMapper;
    @Autowired(required = false)
    private TestcaseMapper testcaseMapper;
    @Autowired(required = false)
    private TestdataMapper testdataMapper;
    @Autowired(required = false)
    private TestdataItemMapper testdataItemMapper;
    @Autowired(required = false)
    private UserKeywordMapper userKeywordMapper;

    @Override
    public void executeTest(Testplan testplan, ResultTestplanBatch resultTestplanBatch, String endRunnerIp) {

        /*获取所有的testcaseTestdata，将每个都封装成task*/
        List<TestcaseTestdata> testcaseTestdataList = testcaseTestdataMapper.findByTestplanId(testplan.getId());

        for(TestcaseTestdata t:testcaseTestdataList){
            /*封装所有的EndRunnerTask*/
            EndRunnerTask task = new EndRunnerTask();

            task.setTaskType("AutoTest");
            task.setEndRunnerIp(endRunnerIp);

            ResultTestcaseTestdata resultTestcaseTestdata = new ResultTestcaseTestdata();
            resultTestcaseTestdata.setTestcaseTestdataId(t.getId());
            resultTestcaseTestdata.setResultTestplanBatchId(resultTestplanBatch.getId());



            /*重头戏，脚本，用键值对的形式，key为fileName,值为code*/
            Map<String,String> nameAndcodes = new HashMap<String,String>();


            /*生成testcase脚本*/
            String[] testcaseWithTestdataCode = generateTestcaseWithTestdataCode(t);
            nameAndcodes.put(testcaseWithTestdataCode[0],testcaseWithTestdataCode[1]);

            /*递归生成所有code*/
            recursiveGenerateCode(nameAndcodes,testcaseWithTestdataCode[1]);

            task.setTestcaseName(testcaseWithTestdataCode[0]);
            task.setResultTestcaseTestdata(resultTestcaseTestdata);
            task.setEndRunnerIp(endRunnerIp);
            task.setCodes(nameAndcodes);
            /*将EndRunnerTask放入queue*/
            Task.tasks.add(task);
        }


    }
    private String[] generateTestcaseWithTestdataCode(TestcaseTestdata t){

        String[] strings = new String[2];

        /*获取testcase*/
        TestcaseVO testcaseVO = testcaseMapper.getTestcaseVOById(t.getTestcaseId());

        /*获取testdata*/
        Testdata testdata = testdataMapper.selectById(t.getTestdataId());

        /*对code进行处理,在code后加variables section就好了*/

        StringBuilder code = new StringBuilder(testcaseVO.getCode());

        /*获取所有testdataitem*/
        List<TestdataItem> tdis = testdataItemMapper.getTestdataItemByTestdataId(t.getTestdataId());
        code.append("\n"+"*** Variables ***"+"\n");
        for(TestdataItem tdi:tdis){
            code.append("\n" + "${").append(tdi.getParameterName()).append("}").append("    ").append(tdi.getParameterValue()).append("    ").append("\n");
        }

        String fileName = testcaseVO.getName();
        strings[0]=fileName;
        strings[1]=code.toString();



        return strings;
    }

    private List<String> parseKeywordNamesFromTestcaseCode(String testcaseCode){
        List<String> kwNames = new ArrayList<>();
        String regStr = "\\b\\w+(?=\\.robot)";
        Pattern kwNamePattern = Pattern.compile(regStr);
        Matcher matcher = kwNamePattern.matcher(testcaseCode);

        while(matcher.find()){
            kwNames.add(matcher.group());
        }

        return kwNames;
    }

    private void recursiveGenerateCode(Map<String,String> map,String code){
        /*递归生成组件脚本*/
        List<String> kwNames = parseKeywordNamesFromTestcaseCode(code);

        if(kwNames.size() == 0){
            return;
        }

        for(String kwName:kwNames){



            List<UserKeyword> list = userKeywordMapper.getList(kwName, -1, null);
            if(list.size() != 1){
                logger.error("kw name wrong!");
                return;
            }

            map.put(kwName, list.get(0).getCode());

            recursiveGenerateCode(map,list.get(0).getCode());


        }
    }

}
